/*
 * This source code is part of TWaver 4.0
 *
 * Serva Software PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 * Copyright 2002 - 2011 Serva Software. All rights reserved.
 */

package demo.network.miscellaneous.limitbound;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.util.Iterator;

import twaver.Element;
import twaver.Node;
import twaver.ResizableNode;
import twaver.TDataBox;
import twaver.TWaverConst;
import twaver.TWaverUtil;
import twaver.network.CanvasCushion;
import twaver.network.InteractionEvent;
import twaver.network.InteractionListener;
import twaver.network.TNetwork;
import demo.DemoPane;

public class LimitBoundDemo extends DemoPane {
	
	private TDataBox box = new TDataBox();
	private TNetwork network = new TNetwork(box);
	private Rectangle limitBounds = new Rectangle(50, 50, 500, 400);
	
	public LimitBoundDemo(){
		this.add(this.network);
		
		this.network.addCanvasCushion(new CanvasCushion(){
			public void paint(Graphics2D g) {
				g.setColor(Color.yellow);
				g.fillRect(limitBounds.x, limitBounds.y, limitBounds.width, limitBounds.height);
			}
		});
		
		for(int i=0; i<5; i++){
			ResizableNode node = new ResizableNode();
			this.box.addElement(node);
			node.putCustomDraw(true);
			node.putBorderVisible(false);
			node.putCustomDrawShapeFactory(TWaverConst.SHAPE_RECTANGLE);
			node.putCustomDrawGradientFactory(TWaverConst.GRADIENT_LINE_NW);
			node.setSize(100, 50);
			node.setLocation(
					limitBounds.x + TWaverUtil.getRandomInt(200), 
					limitBounds.y + TWaverUtil.getRandomInt(200));			
		}
		
		this.network.addInteractionListener(new InteractionListener(){
			public void interactionPerformed(InteractionEvent event) {
				if(event.getType() == InteractionEvent.ELEMENT_LEAP_MOVED 
						|| event.getType() == InteractionEvent.ELEMENT_SMOOTH_MOVED
						|| event.getType() == InteractionEvent.ELEMENT_SMOOTH_MOVING){
					Iterator it = box.getSelectionModel().selection();
					while(it.hasNext()){
						Element element = (Element)it.next();
						if(element instanceof Node){
							Node node = (Node)element;
							if(node.getX() < limitBounds.x){
								node.setLocation(limitBounds.x, node.getY());
							}
							if(node.getY() < limitBounds.y){
								node.setLocation(node.getX(), limitBounds.y);
							}
							if(node.getX()+node.getWidth() > limitBounds.x+limitBounds.width){
								node.setLocation(limitBounds.x+limitBounds.width-node.getWidth(), node.getY());
							}
							if(node.getY()+node.getHeight() > limitBounds.y+limitBounds.height){
								node.setLocation(node.getX(), limitBounds.y+limitBounds.height-node.getHeight());
							}
						}
					}
				}				
			}
		});
	}
}